<template>
  <BasicFormForBOE class="common-search" @register="register">
  </BasicFormForBOE>
</template>
<script lang="ts" setup>
import { BasicFormForBOE, useForm, FormSchema } from '@/components/Form';
import isoWeek from 'dayjs/plugin/isoWeek'
import { dateOptions, getSearchFormSchema, setDisabledDate, pickerType } from './data'
import dayjs from 'dayjs';
import { PropType } from 'vue'; // 添加这一行引入PropType
import { getLastWeekRange } from '@/utils/dateUtil';

const props = defineProps({
  extraSearch: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  },
  // 是否需要周搜索，默认不需要
  disabledOption: {
    type: Array as PropType<string[]>,
    default: () => ['']
    // default: () => ['week']
  },
  // 可以选择的最大日期，用来设置disabledDate
  chooseMaxDate: {
    type: Object,
    default: () => { }
  }
})

defineOptions({ name: 'WeekSelect' })
dayjs.extend(isoWeek)
const emit = defineEmits(['search'])
const handleSearch = async () => {
  const { queryType, startDay, endDay, ...others } = await getFieldsValue()
  if (!queryType) {
    setTimeout(() => handleSearch(), 0)
    return
  }

  // 获取上周的日期范围，确保格式正确
  const defaultWeekRange = getLastWeekRange().map(date => {
    // 如果是周格式，转换为 YYYY-ww 格式
    if (date.includes('W')) {
      return dayjs(date, 'YYYY-[W]ww').format('YYYY-ww');
    }
    return date;
  });

  // 处理用户选择的日期
  const formatWeekDate = (date) => {
    if (!date) return '';
    // 移除可能的 's' 字符和其他非数字/横杠字符
    const cleanDate = date.replace(/[^0-9-]/g, '');
    // 确保格式正确
    return cleanDate.includes('-W')
      ? dayjs(cleanDate, 'YYYY-[W]ww').format('YYYY-ww')
      : cleanDate;
  };

  const params = {
    queryType: pickerType(queryType),
    startDay: startDay ? formatWeekDate(startDay) : defaultWeekRange[0],
    endDay: endDay ? formatWeekDate(endDay) : defaultWeekRange[1],
    ...others
  }

  emit('search', params)
}
const handleReset = async () => {
  const { isRange, format, picker, value } = dateOptions[0]
  await setFieldsValue({
    onlyStartDay: dayjs().format(format)
  })
  await updateSchema([{
    field: 'onlyStartDay',
    ifShow: !isRange,
    componentProps: {
      picker,
      disabledDate: (current) => setDisabledDate(current, props.chooseMaxDate[value]),
      valueFormat: format
    }
  },
  {
    field: '[startDay,endDay]',
    ifShow: isRange,
  }])
}
const [register, { getFieldsValue, updateSchema, setFieldsValue }] = useForm({
  labelWidth: 80,
  schemas: getSearchFormSchema({ disabledOption: props.disabledOption, chooseMaxDate: props.chooseMaxDate }).concat(props.extraSearch),
  autoSubmitOnEnter: false,
  submitFunc: handleSearch,
  submitOnReset: true,
  resetFunc: handleReset
})

defineExpose({
  handleSearch,
  setFieldsValue
})
</script>

<style scoped lang="scss">
.common-search {
  margin-bottom: -12px;
  padding: 12px 8px;
  border-radius: 2px;
  background-color: var(--component-background-color);

  :deep(.ant-form-item) {
    margin-bottom: 12px;
  }

  :deep(.ant-row>.ant-col:last-child) {
    flex: 1;
    max-width: none;
  }
}
</style>